import * as THREE from 'three'
import { LineUtils } from './LineUtils.js'

export class MapUtils {
  constructor (scene, camera, renderer) {
    this.scene = scene
    this.camera = camera
    this.renderer = renderer
    this.lineUtils = LineUtils(scene, renderer, camera)
    this.objects = []
    this.lineSegments = []
  }
  drawMap (mapInfo) {
    this.clearMap()
    const { Points = [], Lines = [], BezierLines = [] } = mapInfo
    this.drawPoints(Points)
    this.drawLines(Lines, BezierLines)
  }

  drawPoints (points) {
    if (!points.length) return;
    const geometry = new THREE.BoxGeometry();
    geometry.translate(0, 0, 0);
    const material = new THREE.MeshPhongMaterial({
      color: 0xbba069,
      flatShading: true
    });
    this.instanceMesh = new THREE.InstancedMesh(geometry, material, points.length);
    this.instanceMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
    const matrix = new THREE.Matrix4();
    const scale = 0.5;
    points.forEach(({ x, y, z }, index) => {
      matrix.identity()
        .setPosition(x, y, z)
        .scale(new THREE.Vector3(scale, scale, scale));
      this.instanceMesh.setMatrixAt(index, matrix);
    });
    this.scene.add(this.instanceMesh);
    this.objects.push(this.instanceMesh);
  }


  drawLines (lines, BezierLines) {
    const L = lines.map(({ start, end }, index) => ({
      id: `line${index}`,
      start: new THREE.Vector3(...start),
      end: new THREE.Vector3(...end),
      color: new THREE.Color(0x00ffff)
    }))
    const BL = BezierLines.map((el, i) => this.lineUtils.generateBezierLines({ ...el, colorFrom: 0x00ffff, colorTo: null, segments: 12, key: i })).flat()
    this.lineSegments = [...L, ...BL]
    this.lineUtils.drawLineSegments(this.lineSegments, { linewidth: 2 })

    const axesHelper = new THREE.AxesHelper(150);
    this.scene.add(axesHelper);

    setTimeout(() => {
      this.highlightLine(['line1', 'line5', 'Bline1-2'])
    }, 1000)
  }

  getPoints () {
    return this.objects;  // 返回存储点Mesh的数组
  }

  getLines () {
    return this.lineUtils.setLineList()  // 返回存储线LineSegments的数组
  }

  highlightLine (lineId) {
    const targetIds = Array.isArray(lineId) ? lineId : [lineId]
    this.lineUtils.highlightLines(targetIds)
  }



  clearMap () {
    this.objects.forEach(object => {
      this.scene.remove(object)
    })
    this.objects = []
    this.lineSegments = []
  }
}

export function initLights (scene) {
  const dirLight1 = new THREE.DirectionalLight(0xffffff, 3)
  dirLight1.position.set(1, 1, 1)
  scene.add(dirLight1)

  const dirLight2 = new THREE.DirectionalLight(0x002288, 3)
  dirLight2.position.set(-1, -1, -1)
  scene.add(dirLight2)

  const ambientLight = new THREE.AmbientLight(0x555555)
  scene.add(ambientLight)

  return { dirLight1, dirLight2, ambientLight }
}